package com.example.springboot.controller;

import com.example.springboot.common.annotation.AutoLog;
import cn.hutool.core.date.DateUtil;
import com.example.springboot.entity.Goods;
import com.example.springboot.entity.User;
import com.example.springboot.service.IGoodsService;
import com.example.springboot.utils.SessionUtils;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Result;
import org.springframework.web.multipart.MultipartFile;
import com.example.springboot.service.ICartService;
import com.example.springboot.entity.Cart;

import org.springframework.web.bind.annotation.RestController;

/**
* <p>
*  前端控制器
* </p>
*
* @author ikun
* @since 2023-04-22
*/
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private ICartService cartService;

    @Resource
    IGoodsService goodsService;

    @AutoLog("新增购物车")
    @PostMapping
    public Result save(@RequestBody Cart cart) {
        User user = SessionUtils.getUser();
        Cart dbCart = cartService.getOne(new QueryWrapper<Cart>().eq("user_id", user.getId()).eq("goods_id", cart.getGoodsId()));
        if (dbCart != null) {
            dbCart.setNum(cart.getNum() + dbCart.getNum());
            cartService.updateById(dbCart);
            return Result.success();
        }

        cart.setUserId(user.getId());
        cart.setCreateTime(DateUtil.now());
        cartService.save(cart);
        return Result.success();
    }

    @AutoLog("编辑购物车")
    @PutMapping
    public Result update(@RequestBody Cart cart) {
        cartService.updateById(cart);
        return Result.success();
    }

    @AutoLog("删除购物车")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        cartService.removeById(id);
        return Result.success();
    }

    @AutoLog("批量删除购物车")
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        cartService.removeByIds(ids);
        return Result.success();
    }

    // 计算购物车选中的商品的总价格
    @PostMapping("/cal")
    public Result cal(@RequestBody List<Cart> carts) {
        BigDecimal total = BigDecimal.ZERO;
        for (Cart cart : carts) {
            Integer goodsId = cart.getGoodsId();
            Goods goods = goodsService.getById(goodsId);
            BigDecimal price = goods.getPrice();
            Integer num = cart.getNum();
            total = total.add(price.multiply(BigDecimal.valueOf(num)));
        }
        return Result.success(total);
    }

    @GetMapping
    public Result findAll() {
        return Result.success(cartService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(cartService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);
        return Result.success(cartService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 前台用户查询购物车
     * 根据当前的用户id进行查询
     * @return
     */
    @GetMapping("/front")
    public Result front() {
        User user = SessionUtils.getUser();
        List<Cart> list = new ArrayList<>();
        if (user != null) {
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>().orderByDesc("id");
            queryWrapper.eq("user_id", user.getId());
            list = cartService.list(queryWrapper);
            for (Cart cart : list) {
                Integer goodsId = cart.getGoodsId();
                Goods goods = goodsService.getById(goodsId);
                cart.setGoods(goods);
            }
        }
        return Result.success(list);
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Cart> list = cartService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Cart信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
    * excel 导入
    * @param file
    * @throws Exception
    */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Cart> list = reader.readAll(Cart.class);

        cartService.saveBatch(list);
        return Result.success();
    }

}
